const db = wx.cloud.database();
const voteimgList = db.collection('voteImgList');
const voteList = db.collection('votes');
let _ = db.command;

Page({
  data: {
    imgList: [],
    vote: false
  },

  onLoad(option) {
    //图片获取
    voteimgList.get().then(res => {
      let list = res.data
      console.log(res)
      this.setData({
        imgList: list
      })
    });
    /**
     * 跳转到该图片适合swiper
    if (option) {
      let index = res.data.findIndex(v => {
        return v.filedid == option
      });
      this.setData({
        index
      })
    } */
  },
  async voteBtn({ currentTarget }) {
    var res = "";
    var voteImgres = "";
    try {
      res = await voteList.where({
        filedId: currentTarget.dataset.id
      }).get();
      if (res.data[0].filedId == currentTarget.dataset.id) {
        // console.log("成功")
        res = await voteList.where({
          filedId: currentTarget.dataset.id
        }).update({
          data: {
            voteCount: _.inc(1),
          }
        });
        voteImgres = await voteimgList.doc(currentTarget.dataset.id).update({
          data: {
            voteCount: _.inc(1),
          }
        });
      }
    } catch (e) {
      res = await voteList.add({
        data: {
          voteCount: 1,
          filedId: currentTarget.dataset.id
        }
      });
      voteImgres = await voteimgList.doc(currentTarget.dataset.id).update({
        data: {
          voteCount: _.inc(1),
        }
      });
    }
    if ((res.errMsg.indexOf('ok') > -1) && (voteImgres.errMsg.indexOf('ok') > -1)) {
      wx.showToast({
        title: '投票成功',
      })
    };
    this.onLoad()
  },

  /**
  * 异步上传
  */
  async long() {
    let res = await wx.chooseImage({
      count: 1,
    })
    // console.log(res)
    let filename = res.tempFilePaths[0];
    let purfileName = filename.split('/').slice(-1)[0];
    res = await wx.cloud.uploadFile({
      cloudPath: 'voteImg/' + purfileName,
      filePath: filename
    })
    // console.log(res)
    let filedid = res.fileID;
    res = await voteimgList.add({
      data: {
        voteCount: 0,
        voteImg: filedid
      }
    });
    if (res.errMsg.indexOf('ok') > -1) {
      wx.showToast({
        title: '上传图片成功',
      });
      this.onLoad(filedid);
    }
  }
})